<template>
  <div class="role">
    <el-card class="searchCard">
      <el-form>
        <el-form-item label="角色名称">
          <el-input v-model="roleInput" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px;">
      <el-button type="primary" icon="Plus" @click="addRole">添加角色</el-button>
      <el-table border style="margin: 20px 0px" :data="roleTable">
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column label="id" align="center" prop="id"></el-table-column>
        <el-table-column label="角色名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" icon="User" size="small" @click="setPermisstion(row)">分配权限</el-button>
            <el-button type="primary" icon="Edit" size="small" @click="updateRole(row)">编辑</el-button>
            <el-popconfirm :title="`你确定要删除${row.roleName}?`" width="260px" @confirm="removeRole(row.id)">
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]" small
        background layout="total, sizes, prev, pager, next, jumper" :total="totalRoleCount"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
    <el-dialog v-model="roleDialog" :title="roleParams.id ? '编辑角色' : '新增角色'">
      <el-form>
        <el-form-item label="角色名称">
          <el-input v-model="roleParams.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRole">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配权限抽屉 -->
    <el-drawer v-model="permissionDrawer" direction="rtl" size="50%">
      <template #header>
        <h4>分配菜单与按钮的权限</h4>
      </template>
      <template #default>
        <el-tree ref="treeNode" style="max-width: 600px" :data="menuArr" show-checkbox node-key="id" default-expand-all
          :default-checked-keys=selectArr :props="defaultProps" />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="permissionDrawer = false">取消</el-button>
          <el-button type="primary" @click="savePermission">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang='ts'>
import { onMounted, ref } from 'vue'
import { getAllRole, addOrUpdateRole, removeRoleAPI, getAllPermissionMenu, savePermissionRole } from '@/api/acl/role/index.ts'
import { ElMessage } from 'element-plus';
// 角色名称输入框绑定的值
let roleInput = ref<string>('')
// 分页器当前页码
let pageNo = ref(1)
// 分页器当前每页数量
let pageSize = ref(10)
// 当前角色总条数
let totalRoleCount = ref(0)
// 列表数据
let roleTable = ref([])
// 编辑和新建角色弹窗
let roleDialog = ref(false)
// 编辑和新建弹窗保存的信息
let roleParams = ref({
  roleName: ''
})
// 分配权限抽屉弹窗
let permissionDrawer = ref(false)
// 所有的菜单复选框
let menuArr = ref([])
// 当前用户选中的菜单复选框
let selectArr = ref([])
// 树形结构dom节点
let treeNode = ref()
// //树形控件的展示数据，需要和menuArr中的数据字段一一对应
const defaultProps = {
  children: 'children',
  label: 'name',
}
//获取全部用户信息的方法|分页器当前页码发生变化的回调
const getHasRole = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager;
  let result = await getAllRole(pageNo.value, pageSize.value, roleInput.value)
  const { code, data } = result
  if (code == 200) {
    roleTable.value = data.records
    totalRoleCount.value = data.total
  } else {
    ElMessage.error('获取角色列表页数据失败')
  }

}
// 搜索角色按钮点击事件
const search = () => {
  console.log('search');
  getHasRole();
}
// 重置角色输入框按钮点击事件
const reset = () => {
  console.log('reset');
  roleInput.value = ''
  getHasRole()
}
// 添加角色按钮点击事件
const addRole = () => {
  console.log('addRole');
  roleParams.value = {
    roleName: '',
  }
  roleDialog.value = true

}
// 分配权限按钮点击事件
const setPermisstion = async (row: any) => {
  console.log(row);
  Object.assign(roleParams.value, row)
  // 调用接口获取所有菜单选项
  let result = await getAllPermissionMenu(row.id)
  const { code, data } = result
  if (code == 200) {
    // 全部菜单权限
    menuArr.value = data
    // 当前用户角色拥有的菜单权限
    selectArr.value = filterSelectArr(menuArr.value, [])
    permissionDrawer.value = true
  }
}
// 通过menuArr中的select的值位true，过滤出当前用户拥有的菜单权限
const filterSelectArr = (menuArr: any, initArr: any) => {
  // 过滤出menuArr中select值位true的菜单id
  menuArr.forEach(menu => {
    // 如果当前menu的level值为4，level为4是最深层的结构，并且select值为true，那么说明当前用户拥有该菜单权限
    if (menu.level == 4 && menu.select == true) {
      initArr.push(menu.id)
    }
    if (menu.children && menu.children.length > 0) {
      // 递归调用filterSelectArr方法进行处理
      filterSelectArr(menu.children, initArr)
    }
  });
  return initArr
}
// 编辑权限
const updateRole = (row) => {
  console.log(row);
  roleDialog.value = true
  Object.assign(roleParams.value, row)
}

// 删除某个角色
const removeRole = async (roleId: number | string) => {
  console.log(roleId);
  let result = await removeRoleAPI(roleId)
  const { code, data } = result
  if (code == 200) {
    ElMessage.success('删除角色成功')
    // 重新调用接口获取列表页数据
    getHasRole()
  } else {
    ElMessage.error('删除角色失败')
  }
}
const handleSizeChange = () => {
  console.log('改变条目数');
  getHasRole()
}
const handleCurrentChange = () => {
  console.log('翻页');
  getHasRole(pageNo.value)
}
// 修改或新建弹窗的保存事件
const saveRole = async () => {
  console.log('save');
  // 发送请求，将新添加的角色名称带给服务器
  let result = await addOrUpdateRole(roleParams.value)
  const { code } = result
  if (code == 200) {
    ElMessage.success(roleParams.value.id ? '修改角色成功' : '新建角色成功')
    // 重新调用接口获取列表页数据
    getHasRole()
  } else {
    ElMessage.error(roleParams.value.id ? '修改角色失败' : '新建角色失败')
  }
  roleDialog.value = false
}
// 保存当前修改的菜单权限事件
const savePermission = async () => {
  // 获取全选的checkbox的id数组
  let allChecked = treeNode.value.getCheckedKeys()
  // 获取半选中状态的checkbox的id数组
  let helfChecked = treeNode.value.getHalfCheckedKeys()
  // 将全选的checkbox和半选中的checkbox数组进行合并
  let checkedBox = allChecked.concat(helfChecked)
  let result = await savePermissionRole(roleParams.value.id, checkedBox)
  const { code } = result
  if (code == 200) {
    ElMessage.success('分配用户权限成功')
  } else {
    ElMessage.error('分配用户权限失败')
  }
  permissionDrawer.value = false

}
onMounted(() => {
  getHasRole()
})

</script>
<style lang="scss" scoped>
.el-input {
  width: 200px;
}

.searchCard {
  .el-form {
    display: flex;
    justify-content: space-between;
  }
}
</style>